package gupao.concurrency.threads;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class ThreadYieldDemo {

    public static void main(String[] args) throws InterruptedException {
        yieldTest();
    }

    private static void yieldTest() throws InterruptedException {
        CountDownLatch l = new CountDownLatch(2);
        AtomicInteger printMonitorLog = new AtomicInteger(0);
        AtomicBoolean stopMonitor = new AtomicBoolean(false);

        Thread t1 = new Thread(() -> {
            List<Long> computeMock = new ArrayList<>();
            for (int i = 0; i < 100; i++) {
                //模拟运算让 t1 执行的慢一点，给monitorThread多点打印的时间
                for(int k = 0 ; k < 10000; k++){
                    Double x = i * Math.sqrt(k) * i;
                    computeMock.add(x.longValue());
                }
                printMonitorLog.incrementAndGet();
//                Thread.yield();
                Utils.sleepIgnoreExp(1); // Thread.yield() 改成 Utils.sleepIgnoreExp(1) 再试试 ？
            }
            stopMonitor.set(true);
            printMonitorLog.set(0);
            l.countDown();
        }, "yield-thread");

        Thread monitorThread = new Thread(() -> {
            while(!stopMonitor.get()){
                if(printMonitorLog.get() > 0){
                    log.info("Monitor Log Flag: {}, {} status: {}", printMonitorLog.get(), t1.getName(), t1.getState());
                }
            }
            l.countDown();
        });

        monitorThread.start();
        t1.start();
        l.await();
    }
}
